import { useState, useCallback, useEffect } from "react";
import { reLaunch } from "@tarojs/taro";
import { Form } from "@nutui/nutui-react-taro";

import { request } from "@/utils/T";
import { EnumRouter } from "@/constants";
import { RespDataType, login, getCaptchaImage } from "./api";

export const useLogin = () => {
  const [form] = Form.useForm();
  const [loading, setLoading] = useState(false);
  const [captchaImageInfo, setCaptchaImageInfo] = useState<RespDataType.ICaptchaImageInfo>({
    img: "",
    key: ""
  });

  useEffect(() => {
    fetchCaptchaImage();
  }, [])

  // 获取验证码图片
  const fetchCaptchaImage = useCallback(() => {
    getCaptchaImage().then((resp) => {
      setCaptchaImageInfo(resp.data);
    })
  }, [])

  const handleSubmit = (values: any) => {
    setLoading(true);
    const {loginName, password, verifyCode } = values;

    login({ loginName, password, verifyCode, verifyKey: captchaImageInfo.key }).then((resp) => {
      request.setToken(resp.data.token);
      setLoading(false);
      reLaunch({url: EnumRouter.home.path});
    }).catch(() => {
      setLoading(false);
    })
  }

  return { loading, handleSubmit, form, fetchCaptchaImage, captchaImageInfo };
}
